<template>

  <BhTable
      ref="tableRef"
      title="菜单管理"
      row-key="id"
      :data="dataList as []"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1700 }"
      :pagination="false"
      :disabled-column-keys="['title']"
      @refresh="search"
  >
    <template #expand-icon="{ expanded }">
      <IconDown v-if="expanded" />
      <IconRight v-else />
    </template>
    <template #top>
      <BhForm  ref="formRef" :columns="queryColumns" :model-value="queryForm"
               :options="options" @search="search" @reset="reset"></BhForm>
    </template>
    <template #toolbar-left>
      <a-button  v-permission="['sys:menu:add']" type="primary"     @click="
              emits('openAdd', {
                parentId: 0,
                sort: getMaxSort(dataList),
              })
            ">
        <template #icon><icon-plus /></template>
        <template #default>新增</template>
      </a-button>
      <a-tooltip content="展开/折叠">
        <a-button @click="onExpanded">
          <template #icon>
            <icon-list v-if="!isExpanded" />
            <icon-mind-mapping v-else />
          </template>
        </a-button>
      </a-tooltip>
    </template>
    <template #title="{ record }">
      <component :is="record.icon" v-if="record.icon" />

      <span style="margin-left: 5px; vertical-align: middle">{{ record.title }}</span>
    </template>
    <template #type="{ record }">
      <a-tag v-if="record.type === 1" color="arcoblue">目录</a-tag>
      <a-tag v-if="record.type === 2" color="green">菜单</a-tag>
      <a-tag v-if="record.type === 3">按钮</a-tag>
    </template>
    <!-- 状态 -->
    <template #status="{ record }">
      <a-space>
        <!-- 菜单状态 -->
        <a-popconfirm
            v-if="hasPermission('sys:role:status')"
            position="top"
            type="warning"
            :content="`确定要将当前节点以及所有子节点改为${
              record.status == 1 ? '停用' : '启用'
            }吗?`"
            @ok="updateStatus(record.id, record.status == 1 ? 2 : 1)"
        >
          <a-tooltip content="点击切换状态">
            <a-tag
                :color="record.status == 1 ? 'arcoblue' : 'orange'"
                class="pointer"
            >
              {{ record.status == 1 ? '启用' : '停用' }}
            </a-tag>
          </a-tooltip>
        </a-popconfirm>
        <a-badge
            v-else
            :status="record.status == 1 ? 'processing' : 'danger'"
            :text="record.status == 1 ? '启用' : '停用'"
        />
      </a-space>
    </template>
    <!-- 是否可见 -->
    <template #hide="{ record }">
      <a-space>
        <!-- 可见状态 -->
        <a-popconfirm
            v-if="hasPermission('sys:role:hide')"
            position="top"
            type="warning"
            :content="`确定要将当前节点以及所有子节点改为${
              record.status == 1 ? '显示' : '隐藏'
            }吗?`"
            @ok="updateHide(record.id, record.hide == 0 ? 1 : 0)"
        >
          <a-tooltip content="点击切换状态">
            <a-tag
                :color="record.hide == 0 ? 'arcoblue' : 'orange'"
                class="pointer"
            >
              {{ record.hide == 0 ? '显示' : '隐藏' }}
            </a-tag>
          </a-tooltip>
        </a-popconfirm>
        <a-badge
            v-else
            :status="record.hide == 0 ? 'processing' : 'danger'"
            :text="record.hide == 0 ? '显示' : '隐藏'"
        />
      </a-space>
    </template>


    <!-- 权限标识 -->
    <template #permission="{ record }">
        <span
            v-if="record.permission"
            class="text-copy"
            @click="copy(record.permission, true)"
        >
          {{ record.permission }}
        </span>
    </template>
    <!-- 组件名称 -->
    <template #component="{ record }">
        <span
            v-if="record.component"
            class="text-copy"
            @click="copy(record.component, true)"
        >
          {{ record.component }}
        </span>
    </template>
    <!-- 路径 -->
    <template #path="{ record }">
        <span
            v-if="record.path"
            class="text-copy"
            @click="copy(record.path, true)"
        >
          {{ record.path }}
        </span>
    </template>
    <template #action="{ record }">
      <a-space>
        <a-link
            v-permission="['sys:menu:add']"
            :disabled="![1, 2].includes(record.type)"
            :title="![1, 2].includes(record.type) ? '不可添加下级菜单' : '新增'"
            @click="
              emits('openAdd', {
                pid: record.id,
                type: record.type,
                sort: getMaxSort(record.children),
              })"
        >
          新增
        </a-link>
        <a-link v-permission="['sys:menu:edit']" title="修改" @click="emits('openUpdate', record)">修改</a-link>
        <a-link v-permission="['system:menu:delete']" status="danger" title="删除" @click="onDelete(record)">删除</a-link>
      </a-space>
    </template>
  </BhTable>
</template>

<script setup lang="ts">
  import {type QueryRequest,type QueryResponse,getList,updateRowStatus,deleteRows, updateRowHide} from '@/api/system/menu';
  import { copy } from '@/hooks/modules/useCopy';
  import usePermission from '@/hooks/permission';
  import { useTable } from '@/hooks/modules/useTable'
  import type { TableInstanceColumns } from '@/components/BhTable/src/types'
  import { isMobile } from '@/utils'
  import type BhTable from '@/components/BhTable/src/BhTable.vue'
  import { type Columns, BhForm, type Options } from '@/components/BhForm'




  const { hasPermission } = usePermission();
  const emits = defineEmits(['openAdd', 'openUpdate']);



  const options: Options = {
    form: { layout: 'inline' },
    grid: { cols: { xs: 1, sm: 1, md: 2, lg: 3, xl: 3, xxl: 2 } },
    fold: { enable: false, index: 1, defaultCollapsed: true },
  }
  const queryForm = reactive<QueryRequest>({
    name: undefined,
  });
  const queryColumns: Columns = reactive([
    {
      label: '菜单标题',
      field: 'name',
      type: 'input',
      props: {
        placeholder: '请输入菜单标题',
      }
    },
  ])

  const {
    tableData,
    loading,
    search,
    handleDelete,
  } = useTable(() => getList(queryForm), { immediate: true })

  const searchData = (title: string) => {
    const loop = (data: QueryResponse[]) => {
      const result = [] as QueryResponse[]
      data.forEach((item: QueryResponse) => {
        if (item.title?.toLowerCase().includes(title.toLowerCase())) {
          result.push({ ...item })
        } else if (item.children) {
          const filterData = loop(item.children)
          if (filterData.length) {
            result.push({
              ...item,
              children: filterData,
            })
          }
        }
      })
      return result
    }
    return loop(tableData.value)
  }


  const title = ref('')

  const dataList = computed(() => {
    if (!title.value) return tableData.value
    return searchData(title.value)
  })

  const columns: TableInstanceColumns[] = [
    { title: '菜单标题', dataIndex: 'title', slotName: 'title', width: 200, fixed: !isMobile() ? 'left' : undefined },
    { title: '类型', dataIndex: 'type', slotName: 'type', align: 'center' },
    { title: '状态', dataIndex: 'status', slotName: 'status', align: 'center' },
    { title: '排序', dataIndex: 'sort', align: 'center', show: false },
    { title: '路由地址', dataIndex: 'path',  slotName: 'path',ellipsis: true, tooltip: true },
    { title: '组件路径', dataIndex: 'component',slotName: 'component', minWidth: 180, ellipsis: true, tooltip: true },
    { title: '权限标识', dataIndex: 'permission',slotName: 'permission', minWidth: 180, ellipsis: true, tooltip: true },
    { title: '隐藏', dataIndex: 'hide', slotName: 'hide', align: 'center' },
    { title: '操作',dataIndex: 'action', slotName: 'action', width: 160, align: 'center',  fixed: !isMobile() ? 'right' : undefined,},
  ]
  // 重置
  const reset = () => {
    queryForm.name = ''
    search()
  }
  // 删除
  const onDelete = (record: QueryResponse) => {
    return handleDelete(() => deleteRows(record.id), {
      content: `是否确定菜单「${record.title}」？`,
      showModal: true,
    })
  }
  const isExpanded = ref(false)
  const tableRef = ref<InstanceType<typeof BhTable>>()

  const onExpanded = () => {
    isExpanded.value = !isExpanded.value
    tableRef.value?.tableRef?.expandAll(isExpanded.value)
  }


  // 更新后回调
  const restartCallback = () => {
    search();
  };

  defineExpose({
    restartCallback,
  });

  // 状态
  const updateStatus = async (id: number, status: number) => {
    await updateRowStatus({ id, status });
    search()
  };
  // 隐藏
  const updateHide = async (id: number, hide: number) => {
    await updateRowHide({ id, hide });
    search()
  };

  //获取最大排序
  const getMaxSort = (array: QueryResponse[]) => {
    if (array?.length) {
      return array[array.length - 1].sort;
    }
    return 0;
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
